package com.orifine.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import org.springframework.stereotype.Service;



/**
 * 国际化服务，带缓存，第一次使用服务时将从baseDir目录上指定的资源文件加载到缓存中
 *
 */
@Service
public abstract class ResourceInternationalization implements Internationalization {
	private Map<String, Properties> message = new HashMap<String, Properties>();
	
	/**
	 * @see ResourceInternationalization#getMessage(String, String)
	 */
	public String getMessage(Locale locale, String messageName){
		Properties properties = load(locale.toString().toLowerCase());
		return properties.getProperty(messageName);
	}
	
	public String getMessage(String messageName){
		return load().getProperty(messageName);
	}
	
	/**
	 * 加载资源文件
	 * @param localeName 加载的语言
	 * @return 返回资源对象
	 */
	private Properties load(String localeName){
		if(!message.containsKey(localeName)){
			URL url = this.getClass().getResource(this.getClass().getSimpleName()+"_"+localeName+".properties");
			if(url != null){
				File file = new File(url.getFile());
				Properties properties = new Properties();
				try {
					properties.load(new FileInputStream(file));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				message.put(localeName, properties);
				return properties;
			}
		}
		if(message.containsKey(localeName)){
			return message.get(localeName);
		} else {
			return load();
		}
	}
	
	private static final String PROPERTIES = "Properties";
	private static final String PROPERTIES_SUFFIX = ".properties";
	/**
	 * 加载资源文件
	 * @return 返回资源对象
	 */
	private Properties load(){
		if(!message.containsKey("default")){
			String name = this.getClass().getSimpleName();
			if(name.endsWith(PROPERTIES)){
				name = name.substring(0, name.length()-PROPERTIES.length());
			}
			URL url = this.getClass().getResource(name+PROPERTIES_SUFFIX);
			File file = new File(url.getFile());
			Properties properties = new Properties();
			try {
				properties.load(new FileInputStream(file));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			message.put("default", properties);
		}
		return message.get("default");
	}
	
	public static String get(Locale locale, String messageName) {
		throw new RuntimeException("这里不能调用，需要继承调用");
	}

	public static String get(String messageName) {
		throw new RuntimeException("这里不能调用，需要继承调用");
	}
}
